/**
 * Created by levy on 2018/7/22.
 */
import cookie from 'js-cookie'
import cookieKeys from '@const/cookie-keys'

// 客户端鉴权
export default {
  async created() {
    if (process.env.NO_LOGIN > 0) return

    let cookieInfo = {}

    cookieKeys.forEach(key => {
      cookieInfo[key] = cookie.get(key)
    })

    // 未登录
    if (!cookieInfo.userId || !cookieInfo.token) {
      window.location.href = this.$store.state.toNavPage + '?errorDesc=用户鉴权，获取不到用户信息：auth.js:'
    } else if (!this.$store.state.userId) {
      // 已登录但因为刷新, 状态  丢失
      this.$store.commit('update', cookieInfo)
      // 如果是系统导航页面，则不需要获取菜单信息
      if (this.$route.path === '/') {
        return
      }
      try {
        await this.$store.dispatch('fetchUserAndMenuList', {
          userId: cookieKeys.userId
        })
      } catch (e) {
        let path = this.$router.options.base
        cookie.remove('token', { path })
        cookie.remove('userId', { path })

        console.error('auth error: ', e)
        window.location.href = this.$store.state.toNavPage + '?errorDesc=鉴权时，获取菜单出错：'
      }
    }
  }
}
